import {
  DataPermissionField,
  DataPermissionFieldDecisionSymbol,
  RuleParams,
} from 'admin/schema/DataPermission';
import { getDataPermissionFieldDecisionSymbols } from 'admin/servers/servers';
import { Form, Input, Select, Space } from 'antd';
import { FormInstance, Rule } from 'antd/lib/form';
import React from 'react';
import { verifyNull } from 'utils/tools';
const Option = Select.Option;

/**
 * RuleItem入参
 */
interface RuleItemOption {
  //设置数据源表属性列表
  resourceFieldList: DataPermissionField[];
  //name
  name: number;

  //高级规则回显列表
  ruleParamsList: RuleParams[];
  //是否高级规则
  advancedRule: boolean;
  //表单
  ruleForm: FormInstance<any>;
}

/**
 * RuleItem 维护的状态
 */
interface RuleItemState extends RuleItemOption {
  //比较值文本框是否展示
  fieldValueDisable: boolean;

  //选中的属性字段
  dataPermissionFieldKey: string;

  //判定符列表
  decisionSymbolKeyList: DataPermissionFieldDecisionSymbol[];

  flag: boolean;
}

export class RuleItem extends React.Component<RuleItemOption, RuleItemState> {
  constructor(args: RuleItemOption) {
    super(args);
    this.state = {
      fieldValueDisable: false,
      dataPermissionFieldKey: '',
      name: args.name,
      decisionSymbolKeyList: [],
      resourceFieldList: args.resourceFieldList,
      ruleParamsList: args.ruleParamsList,
      advancedRule: args.advancedRule,
      ruleForm: args.ruleForm,
      flag: false,
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps: any) {
    const { flag, ruleForm } = this.state;
    this.setState(
      {
        resourceFieldList: nextProps.resourceFieldList,
        advancedRule: nextProps.advancedRule,
        name: nextProps.name,
      },
      () => {
        const { name } = this.state;
        const ruleParams = nextProps.ruleParamsList[name];
        if (ruleParams) {
          let fieldKey;
          const val = ruleForm.getFieldsValue();
          const params = val?.ruleParams[name] as RuleParams;
          if (!params || !params.fieldKey) {
            fieldKey = ruleParams.fieldKey;
          } else {
            fieldKey = params.fieldKey;
          }

          if (params && params.fieldKey) {
            if (!flag) {
              this.fetchFieldDecisionSymbolList(fieldKey ? fieldKey : '');
              this.setState({
                flag: true,
              });
            }
          }

          if (params) {
            this.setState({
              fieldValueDisable: params.decisionSymbolKey === 'selfOrganization' ? true : false,
            });
          }
        }
      }
    );
  }

  render() {
    const { resourceFieldList, fieldValueDisable, name, decisionSymbolKeyList } = this.state;
    return (
      <>
        <Space style={{ display: 'flex', marginBottom: 8 }} align="baseline">
          {name > 0 ? (
            <Form.Item
              name={[name, 'relationSymbol']}
              rules={this.getRules('relationSymbol', '请选择关联符')}
            >
              <Select style={{ width: 130 }} placeholder="请选择关联符">
                <Option key="And" value="And">
                  And
                </Option>
                <Option key="Or" value="Or">
                  Or
                </Option>
              </Select>
            </Form.Item>
          ) : (
            ''
          )}
          <Form.Item
            name={[name, 'fieldKey']}
            rules={this.getRules('fieldKey', '请选择属性字段')}
            style={{ marginLeft: name === 0 ? 138 : 0 }}
            dependencies={['resourceKeys']}
          >
            <Select
              allowClear
              style={{ width: 140 }}
              placeholder="请选择属性字段"
              // defaultValue={defalueValue?.fieldName}
              onChange={(val: string) => {
                console.log('fieldKey=' + val);
                this.fetchFieldDecisionSymbolList(val);
                this.clearRuleParamsItem();
              }}
            >
              {resourceFieldList?.map((item: { fieldKey: any; fieldName: any }) => {
                return (
                  <Option key={item.fieldKey} value={item.fieldKey}>
                    {item.fieldName}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            name={[name, 'decisionSymbolKey']}
            style={{ width: 150 }}
            rules={this.getRules('decisionSymbolKey', '请选择判定符')}
            dependencies={['fieldKey']}
          >
            {/* <PageSelect
              allowClear
              placeholder="请选择判定符"
              fetchData={this.fetchFieldDecisionSymbolList}
              value={decisionSymbolKeyDefalutValue}
              onChange={(
                val: string | number | { label: string; value: string | number }[]
              ): void => {
                this.setState({
                  fieldValueDisable: val === 'selfOrganization' ? true : false,
                });
              }}
            /> */}
            <Select
              allowClear
              style={{ width: 140 }}
              placeholder="请选择判定符"
              // defaultValue={defalueValue?.decisionSymbolName}
              defaultValue={decisionSymbolKeyList[0]?.decisionSymbolKey}
              onChange={(val: string) => {
                this.setState({
                  fieldValueDisable: val === 'selfOrganization' ? true : false,
                });
                if (val === 'selfOrganization') {
                  this.clearFieldValue();
                }
              }}
            >
              {decisionSymbolKeyList?.map(
                (item: { decisionSymbolKey: any; decisionSymbolName: any }) => {
                  return (
                    <Option key={item.decisionSymbolKey} value={item.decisionSymbolKey}>
                      {item.decisionSymbolName}
                    </Option>
                  );
                }
              )}
            </Select>
          </Form.Item>
          <Form.Item
            name={[name, 'fieldValue']}
            rules={this.getRules('fieldValue', '请输入比较值')}
          >
            <Input placeholder="请输入比较值" style={{ width: 110 }} disabled={fieldValueDisable} />
          </Form.Item>
        </Space>
      </>
    );
  }

  // fetchResourceFieldList = () => {
  //   const { resourceKeyList } = this.state;
  //   if (resourceKeyList.length === 0) {
  //     return;
  //   }
  //   getDataPermissionResourceFields(resourceKeyList)
  //     .then(res => {
  //       this.setState({
  //         resourceFieldList: res.data,
  //       });
  //     })
  //     .catch(error => {
  //       console.error(`系统异常: ${JSON.stringify(error)}`);
  //     });
  // };

  /** 获取判定符列表 */
  fetchFieldDecisionSymbolList = (value: string) => {
    if (!value) {
      return;
    }
    getDataPermissionFieldDecisionSymbols(value)
      .then(res => {
        this.setState({
          decisionSymbolKeyList: res.data,
        });
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  /**
   * pageSelect获取判定符列表的函数
   */
  // fetchFieldDecisionSymbolList = (arg: FetchDataParam): FetchDataResponse => {
  //   const { dataPermissionFieldKey } = this.state;
  //   console.log('dataPermissionFieldKey:' + dataPermissionFieldKey);
  //   return new Promise(resolve => {
  //     getDataPermissionFieldDecisionSymbols(dataPermissionFieldKey)
  //       .then(res => {
  //         if (!res.data) {
  //           resolve({
  //             data: [],
  //             total: 1,
  //           });
  //           return;
  //         }
  //         resolve({
  //           data: res.data.map(item => {
  //             return {
  //               label: item.decisionSymbolName,
  //               value: item.decisionSymbolKey,
  //             };
  //           }),
  //           total: res.count as number,
  //         });
  //       })
  //       .catch(error => {
  //         console.error(`系统异常: ${JSON.stringify(error)}`);
  //       });
  //   });
  // };

  /**获取校验规则 */
  getRules = (key: string, message?: string): Rule[] => {
    const { fieldValueDisable, advancedRule } = this.state;
    const ruleMap = new Map();

    if (advancedRule) {
      ruleMap.set('fieldKey', verifyNull(message));
      ruleMap.set('relationSymbol', verifyNull(message));
      ruleMap.set('decisionSymbolKey', verifyNull(message));

      if (!fieldValueDisable) {
        ruleMap.set('fieldValue', verifyNull(message));
      }
    }

    return ruleMap.get(key);
  };

  clearRuleParamsItem = () => {
    const { ruleForm, name } = this.state;
    const val = ruleForm.getFieldsValue();
    const ruleParams = [] as any;
    if (val.ruleParams) {
      val.ruleParams.map((item: any, index: number) => {
        const ruleParam = {} as RuleParams;
        ruleParam.fieldKey = item.fieldKey ? item.fieldKey : null;
        ruleParam.fieldValue = item.fieldValue ? item.fieldValue : null;
        ruleParam.relationSymbol = item.relationSymbol ? item.relationSymbol : null;
        ruleParams.push(ruleParam);
        if (index === name) {
          ruleParam.decisionSymbolKey = null;
        } else {
          ruleParam.decisionSymbolKey = item.decisionSymbolKey ? item.decisionSymbolKey : null;
        }
      });
    }
    ruleForm.setFieldsValue({
      ruleParams: ruleParams,
    });
  };

  clearFieldValue = () => {
    const { ruleForm, name } = this.state;
    const val = ruleForm.getFieldsValue();
    const ruleParams = [] as any;
    if (val.ruleParams) {
      val.ruleParams.map((item: any, index: number) => {
        const ruleParam = {} as RuleParams;
        ruleParam.fieldKey = item.fieldKey ? item.fieldKey : null;
        ruleParam.relationSymbol = item.relationSymbol ? item.relationSymbol : null;
        ruleParam.decisionSymbolKey = item.decisionSymbolKey ? item.decisionSymbolKey : null;
        ruleParams.push(ruleParam);
        if (index === name) {
          ruleParam.fieldValue = null;
        } else {
          ruleParam.fieldValue = item.fieldValue ? item.fieldValue : null;
        }
      });
    }
    ruleForm.setFieldsValue({
      ruleParams: ruleParams,
    });
  };
}
